<template>
  <div class="dev-tools">
    <ToolContainer
      tool-name="开发工具"
      title="开发者专用工具集"
      description="为开发者提供JSON格式化、正则测试、时间戳转换等实用工具"
      :header-icon="Monitor"
      icon-color="#909399"
      default-tab="json"
      @tab-change="handleTabChange"
    >
      <template #tabs>
        <!-- JSON格式化标签页 -->
        <el-tab-pane label="JSON格式化" name="json">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="json-section">
                <el-form label-width="100px">
                  <el-form-item label="JSON数据">
                    <el-input
                      v-model="jsonInput"
                      type="textarea"
                      :rows="8"
                      placeholder="请输入JSON数据..."
                    />
                  </el-form-item>
                  <el-form-item label="缩进设置">
                    <el-radio-group v-model="jsonIndent">
                      <el-radio :label="2">2个空格</el-radio>
                      <el-radio :label="4">4个空格</el-radio>
                      <el-radio label="tab">Tab缩进</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="formatJson"
                :loading="loading"
                :disabled="!jsonInput.trim()"
              >
                格式化
              </el-button>
              <el-button 
                type="success" 
                @click="compressJson"
                :loading="loading"
                :disabled="!jsonInput.trim()"
              >
                压缩
              </el-button>
              <el-button 
                @click="validateJson"
                :disabled="!jsonInput.trim()"
              >
                验证
              </el-button>
            </template>

            <template #result>
              <div v-if="jsonOutput" class="result-display">
                <h4>格式化结果：</h4>
                <el-input
                  v-model="jsonOutput"
                  type="textarea"
                  :rows="10"
                  readonly
                />
                <div class="result-actions">
                  <el-button type="success" @click="copyResult('json')">
                    复制结果
                  </el-button>
                  <el-button @click="clearOutput('json')">
                    清空结果
                  </el-button>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>

        <!-- 正则表达式测试标签页 -->
        <el-tab-pane label="正则测试" name="regex">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="regex-section">
                <el-form label-width="100px">
                  <el-form-item label="正则表达式">
                    <el-input
                      v-model="regexPattern"
                      placeholder="请输入正则表达式..."
                    />
                  </el-form-item>
                  <el-form-item label="匹配标志">
                    <el-checkbox-group v-model="regexFlags">
                      <el-checkbox label="g">全局匹配 (g)</el-checkbox>
                      <el-checkbox label="i">忽略大小写 (i)</el-checkbox>
                      <el-checkbox label="m">多行模式 (m)</el-checkbox>
                      <el-checkbox label="s">单行模式 (s)</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                  <el-form-item label="测试文本">
                    <el-input
                      v-model="regexTestText"
                      type="textarea"
                      :rows="6"
                      placeholder="请输入要测试的文本..."
                    />
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="testRegex"
                :disabled="!regexPattern.trim() || !regexTestText.trim()"
              >
                测试匹配
              </el-button>
              <el-button 
                type="success" 
                @click="replaceRegex"
                :disabled="!regexPattern.trim() || !regexTestText.trim()"
              >
                替换文本
              </el-button>
            </template>

            <template #result>
              <div v-if="regexResult" class="result-display">
                <h4>匹配结果：</h4>
                <div class="regex-matches">
                  <div v-if="regexResult.matches.length > 0">
                    <p><strong>找到 {{ regexResult.matches.length }} 个匹配项：</strong></p>
                    <div v-for="(match, index) in regexResult.matches" :key="index" class="match-item">
                      <span class="match-index">{{ index + 1 }}.</span>
                      <span class="match-text">{{ match }}</span>
                    </div>
                  </div>
                  <div v-else>
                    <el-alert title="未找到匹配项" type="warning" :closable="false" />
                  </div>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>

        <!-- 时间戳转换标签页 -->
        <el-tab-pane label="时间戳转换" name="timestamp">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="timestamp-section">
                <el-form label-width="120px">
                  <el-form-item label="当前时间戳">
                    <el-input
                      :value="currentTimestamp"
                      readonly
                    />
                    <el-button @click="updateCurrentTime" style="margin-left: 10px;">
                      刷新
                    </el-button>
                  </el-form-item>
                  <el-form-item label="时间戳输入">
                    <el-input
                      v-model="timestampInput"
                      placeholder="请输入时间戳（秒或毫秒）..."
                    />
                  </el-form-item>
                  <el-form-item label="日期时间输入">
                    <el-date-picker
                      v-model="dateTimeInput"
                      type="datetime"
                      placeholder="选择日期时间"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      style="width: 100%;"
                    />
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="convertTimestamp"
                :disabled="!timestampInput.trim()"
              >
                时间戳转日期
              </el-button>
              <el-button 
                type="success" 
                @click="convertDateTime"
                :disabled="!dateTimeInput"
              >
                日期转时间戳
              </el-button>
            </template>

            <template #result>
              <div v-if="timestampResult" class="result-display">
                <h4>转换结果：</h4>
                <div class="timestamp-results">
                  <div class="result-item">
                    <span class="label">时间戳（秒）：</span>
                    <span class="value">{{ timestampResult.seconds }}</span>
                  </div>
                  <div class="result-item">
                    <span class="label">时间戳（毫秒）：</span>
                    <span class="value">{{ timestampResult.milliseconds }}</span>
                  </div>
                  <div class="result-item">
                    <span class="label">格式化时间：</span>
                    <span class="value">{{ timestampResult.formatted }}</span>
                  </div>
                  <div class="result-item">
                    <span class="label">ISO格式：</span>
                    <span class="value">{{ timestampResult.iso }}</span>
                  </div>
                </div>
                <div class="result-actions">
                  <el-button type="success" @click="copyResult('timestamp')">
                    复制结果
                  </el-button>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>

        <!-- URL编码解码标签页 -->
        <el-tab-pane label="URL编码" name="url">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="url-section">
                <el-form label-width="100px">
                  <el-form-item label="输入内容">
                    <el-input
                      v-model="urlInput"
                      type="textarea"
                      :rows="6"
                      placeholder="请输入需要编码/解码的URL或文本..."
                    />
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="encodeUrl"
                :disabled="!urlInput.trim()"
              >
                URL编码
              </el-button>
              <el-button 
                type="success" 
                @click="decodeUrl"
                :disabled="!urlInput.trim()"
              >
                URL解码
              </el-button>
              <el-button 
                type="warning" 
                @click="encodeComponent"
                :disabled="!urlInput.trim()"
              >
                组件编码
              </el-button>
            </template>

            <template #result>
              <div v-if="urlOutput" class="result-display">
                <h4>编码/解码结果：</h4>
                <el-input
                  v-model="urlOutput"
                  type="textarea"
                  :rows="6"
                  readonly
                />
                <div class="result-actions">
                  <el-button type="success" @click="copyResult('url')">
                    复制结果
                  </el-button>
                  <el-button @click="clearOutput('url')">
                    清空结果
                  </el-button>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>
      </template>
    </ToolContainer>

    <!-- 功能介绍组件 -->
    <FeatureIntro
      :title="featureConfig.title"
      :description="featureConfig.description"
      :header-icon="featureConfig.headerIcon"
      :features="featureConfig.features"
      :initial-visible="showIntro"
      @close="showIntro = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Monitor } from '@element-plus/icons-vue'
import ToolContainer from '@/components/ToolContainer.vue'
import ToolSection from '@/components/ToolSection.vue'
import FeatureIntro from '@/components/FeatureIntro.vue'
import { featuresConfig } from '@/config/featuresConfig.js'

// 基础数据
const loading = ref(false)
const showIntro = ref(true)
const featureConfig = featuresConfig.devTools

// JSON相关
const jsonInput = ref('')
const jsonOutput = ref('')
const jsonIndent = ref(2)

// 正则表达式相关
const regexPattern = ref('')
const regexFlags = ref(['g'])
const regexTestText = ref('')
const regexResult = ref(null)

// 时间戳相关
const currentTimestamp = ref('')
const timestampInput = ref('')
const dateTimeInput = ref('')
const timestampResult = ref(null)

// URL编码相关
const urlInput = ref('')
const urlOutput = ref('')

// 事件处理
function handleTabChange(tabName: string) {
  console.log('切换到标签页:', tabName)
}

// JSON格式化功能
function formatJson() {
  if (!jsonInput.value.trim()) {
    ElMessage.warning('请输入JSON数据')
    return
  }
  
  loading.value = true
  setTimeout(() => {
    try {
      const parsed = JSON.parse(jsonInput.value)
      const indent = jsonIndent.value === 'tab' ? '\t' : jsonIndent.value
      jsonOutput.value = JSON.stringify(parsed, null, indent)
      ElMessage.success('JSON格式化完成')
    } catch (error) {
      ElMessage.error('JSON格式错误：' + error.message)
    } finally {
      loading.value = false
    }
  }, 300)
}

function compressJson() {
  if (!jsonInput.value.trim()) {
    ElMessage.warning('请输入JSON数据')
    return
  }
  
  loading.value = true
  setTimeout(() => {
    try {
      const parsed = JSON.parse(jsonInput.value)
      jsonOutput.value = JSON.stringify(parsed)
      ElMessage.success('JSON压缩完成')
    } catch (error) {
      ElMessage.error('JSON格式错误：' + error.message)
    } finally {
      loading.value = false
    }
  }, 300)
}

function validateJson() {
  if (!jsonInput.value.trim()) {
    ElMessage.warning('请输入JSON数据')
    return
  }
  
  try {
    JSON.parse(jsonInput.value)
    ElMessage.success('JSON格式正确')
  } catch (error) {
    ElMessage.error('JSON格式错误：' + error.message)
  }
}

// 正则表达式功能
function testRegex() {
  if (!regexPattern.value.trim() || !regexTestText.value.trim()) {
    ElMessage.warning('请输入正则表达式和测试文本')
    return
  }
  
  try {
    const flags = regexFlags.value.join('')
    const regex = new RegExp(regexPattern.value, flags)
    const matches = regexTestText.value.match(regex) || []
    
    regexResult.value = {
      matches: matches,
      pattern: regexPattern.value,
      flags: flags
    }
    
    ElMessage.success(`找到 ${matches.length} 个匹配项`)
  } catch (error) {
    ElMessage.error('正则表达式错误：' + error.message)
  }
}

function replaceRegex() {
  // 这里可以添加替换功能
  ElMessage.info('替换功能开发中...')
}

// 时间戳转换功能
function updateCurrentTime() {
  currentTimestamp.value = Math.floor(Date.now() / 1000).toString()
}

function convertTimestamp() {
  if (!timestampInput.value.trim()) {
    ElMessage.warning('请输入时间戳')
    return
  }
  
  try {
    let timestamp = parseInt(timestampInput.value)
    
    // 判断是秒还是毫秒
    if (timestamp.toString().length === 10) {
      timestamp = timestamp * 1000
    }
    
    const date = new Date(timestamp)
    
    timestampResult.value = {
      seconds: Math.floor(timestamp / 1000),
      milliseconds: timestamp,
      formatted: date.toLocaleString('zh-CN'),
      iso: date.toISOString()
    }
    
    ElMessage.success('时间戳转换完成')
  } catch (error) {
    ElMessage.error('时间戳格式错误')
  }
}

function convertDateTime() {
  if (!dateTimeInput.value) {
    ElMessage.warning('请选择日期时间')
    return
  }
  
  try {
    const date = new Date(dateTimeInput.value)
    const timestamp = date.getTime()
    
    timestampResult.value = {
      seconds: Math.floor(timestamp / 1000),
      milliseconds: timestamp,
      formatted: date.toLocaleString('zh-CN'),
      iso: date.toISOString()
    }
    
    ElMessage.success('日期转换完成')
  } catch (error) {
    ElMessage.error('日期格式错误')
  }
}

// URL编码解码功能
function encodeUrl() {
  if (!urlInput.value.trim()) {
    ElMessage.warning('请输入需要编码的内容')
    return
  }
  
  try {
    urlOutput.value = encodeURI(urlInput.value)
    ElMessage.success('URL编码完成')
  } catch (error) {
    ElMessage.error('编码失败：' + error.message)
  }
}

function decodeUrl() {
  if (!urlInput.value.trim()) {
    ElMessage.warning('请输入需要解码的内容')
    return
  }
  
  try {
    urlOutput.value = decodeURI(urlInput.value)
    ElMessage.success('URL解码完成')
  } catch (error) {
    ElMessage.error('解码失败：' + error.message)
  }
}

function encodeComponent() {
  if (!urlInput.value.trim()) {
    ElMessage.warning('请输入需要编码的内容')
    return
  }
  
  try {
    urlOutput.value = encodeURIComponent(urlInput.value)
    ElMessage.success('组件编码完成')
  } catch (error) {
    ElMessage.error('编码失败：' + error.message)
  }
}

// 工具函数
function clearOutput(type: string) {
  switch (type) {
    case 'json':
      jsonOutput.value = ''
      break
    case 'url':
      urlOutput.value = ''
      break
  }
  ElMessage.info('已清空结果')
}

function copyResult(type: string) {
  let text = ''
  switch (type) {
    case 'json':
      text = jsonOutput.value
      break
    case 'timestamp':
      if (timestampResult.value) {
        text = `时间戳（秒）：${timestampResult.value.seconds}\n时间戳（毫秒）：${timestampResult.value.milliseconds}\n格式化时间：${timestampResult.value.formatted}\nISO格式：${timestampResult.value.iso}`
      }
      break
    case 'url':
      text = urlOutput.value
      break
  }
  
  if (text) {
    navigator.clipboard.writeText(text)
    ElMessage.success('结果已复制到剪贴板')
  } else {
    ElMessage.warning('没有可复制的内容')
  }
}

// 初始化
onMounted(() => {
  updateCurrentTime()
  // 每秒更新当前时间戳
  setInterval(updateCurrentTime, 1000)
})
</script>

<style scoped>
.dev-tools {
  position: relative;
}

.json-section,
.regex-section,
.timestamp-section,
.url-section {
  width: 100%;
}

.result-display {
  width: 100%;
}

.result-display h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary, #303133);
}

.result-actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

/* 正则匹配结果样式 */
.regex-matches {
  background: var(--el-bg-color-page, #fafbfc);
  border-radius: 8px;
  padding: 16px;
  border: 1px solid var(--el-border-color-lighter, #f2f6fc);
}

.match-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  padding: 8px;
  background: var(--el-bg-color, #ffffff);
  border-radius: 4px;
  border: 1px solid var(--el-border-color-light, #e4e7ed);
}

.match-index {
  font-weight: 600;
  color: var(--el-color-primary, #409eff);
  min-width: 24px;
}

.match-text {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  background: var(--el-color-primary-light-9, #ecf5ff);
  padding: 2px 6px;
  border-radius: 3px;
  color: var(--el-text-color-primary, #303133);
}

/* 时间戳结果样式 */
.timestamp-results {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 12px;
  background: var(--el-bg-color-page, #fafbfc);
  border-radius: 6px;
  border: 1px solid var(--el-border-color-lighter, #f2f6fc);
}

.result-item .label {
  font-weight: 500;
  color: var(--el-text-color-regular, #606266);
  min-width: 120px;
}

.result-item .value {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  color: var(--el-text-color-primary, #303133);
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .result-actions {
    flex-direction: column;
  }
  
  .result-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .result-item .label {
    min-width: auto;
  }
}
</style> 